import os
import re


def depends(file: str):
    if not os.path.exists(file):
        return []

    with os.popen('ldd {0}'.format(file)) as fd:
        lines = fd.readlines()

    if len(lines) == 0:
        return []

    files = []
    for item in lines:
        match = re.search(r'=>(?P<fd>.*?)\s+\(0x.*?\)', item)
        if match is None:
            continue
        fd = match.group('fd')
        fd = fd.replace('\n', '').replace('\t', '').replace(' ', '')
        if fd == '':
            continue
        files.append(fd)
    return files


def analyse(args: list):
    # 依赖列表
    data = []
    # 已分析过的文件
    ldd = []

    def _analyse(fs: list):
        for item in fs:
            # 已分析过
            if item in ldd:
                continue

            # 分析
            files = depends(item)
            # 添加到已分析列表中
            ldd.append(item)

            if len(files) == 0:
                continue

            # 添加到依赖列表中
            for file in files:
                if file in data:
                    continue
                data.append(file)

            # 递归分析
            _analyse(files)

    _analyse(args)
    return data
